#include "PreCompile.h"
#include "EventSelect.h"

using namespace std;

void CEventSelect::Release()
{
	delete this;
}

bool CEventSelect::Initialize()
{
	WSADATA wsaData;
	WSAStartup(0x0002, &wsaData);

	m_listenSocket = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, 0, 0, 0);

	sockaddr_in serverAddr;
	serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
	serverAddr.sin_family = AF_INET;
	serverAddr.sin_port = htons(1024);
	int serverAddrLen = sizeof(serverAddr);

	bind(m_listenSocket, (sockaddr*)&serverAddr, sizeof(serverAddr));
	listen(m_listenSocket, 5);
	WSAEVENT hEvent = WSACreateEvent();
	WSAEventSelect(m_listenSocket, hEvent, FD_ACCEPT | FD_READ | FD_WRITE | FD_CLOSE);
	m_peers.push_back(CPeer(m_listenSocket, hEvent));

	return true;
}

void CEventSelect::Stop()
{
	m_bStop = true;
}

void CEventSelect::Do()
{
	while(!m_bStop)
	{
		WSAEVENT* pEvents = new WSAEVENT[m_peers.size()];
		for(int index = 0; index < m_peers.size(); ++index)
		{
			pEvents[index] = m_peers[index].hEvent;
		}
		WaitForMultipleObjects(m_peers.size(), pEvents, false, INFINITE);

	}
}
